/**
 * @Author xy
 * @Date 2020/7/14 20:56
 * @Description
 */
package main.other.algorithm;

/**
 * @desc 二分查询（非递归方式）
 * 案例：
 * {1,3,8,10,11,67,100}，编程实现二分查找，要求使用非递归方式完成。
 * @Author xw
 * @Date 2019/9/27
 */
public class BinarySearchNonRecursive {
    public static void main(String[] args) {
        int[] arr = {1, 3, 8, 10, 11, 67, 100};
        int index = binarySearch(arr,1);
        if(index==-1){
            System.out.println("未找到指定值");
        }else {
            System.out.println("找到了，下标为："+index);
        }
    }

    private static int binarySearch(int[] arr, int target){
        int left = 0;
        int right = arr.length-1;
        while (left<=right){
            int mid = (left+right)/2;
            if(arr[mid]==target){
                return mid;
            }else if(arr[mid]<target){
                left = mid+1;
            }else{
                right = mid-1;
            }
        }
        return -1;
    }
}
